// pages/history/history.js
const app = getApp();
const { deviceApi } = require('../../services/api');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    historyData: [],
    isLoading: true,
    currentMonth: '',
    showError: false,
    errorMessage: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('历史记录页面加载');
    
    // 获取当前月份
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    this.setData({
      currentMonth: `${year}年${month}月`
    });
    
    // 加载历史数据
    this.loadHistoryData();
  },
  
  /**
   * 加载历史数据
   */
  loadHistoryData: function() {
    this.setData({ isLoading: true, showError: false });
    
    // 模拟获取历史数据
    setTimeout(() => {
      // 生成模拟数据
      const historyData = this.generateMockData();
      
      this.setData({
        historyData: historyData,
        isLoading: false
      });
    }, 1000);
  },
  
  /**
   * 生成模拟数据
   */
  generateMockData: function() {
    const data = [];
    const now = new Date();
    
    // 生成过去30天的数据
    for (let i = 0; i < 30; i++) {
      const date = new Date();
      date.setDate(now.getDate() - i);
      
      // 格式化日期
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const formattedDate = `${year}-${month}-${day}`;
      
      // 随机生成空气质量数据
      const score = Math.floor(Math.random() * 50) + 50; // 50-100之间
      let level = '';
      if (score >= 90) level = '优';
      else if (score >= 80) level = '良';
      else if (score >= 70) level = '中等';
      else if (score >= 60) level = '一般';
      else level = '较差';
      
      // 随机生成其他数据
      const temperature = (20 + Math.random() * 10).toFixed(1);
      const humidity = Math.floor(Math.random() * 40) + 40; // 40-80之间
      const co2 = Math.floor(Math.random() * 500) + 400; // 400-900之间
      const pm25 = Math.floor(Math.random() * 30) + 10; // 10-40之间
      const formaldehyde = (0.01 + Math.random() * 0.09).toFixed(2); // 0.01-0.1之间
      
      data.push({
        date: formattedDate,
        displayDate: `${month}月${day}日`,
        score: score,
        level: level,
        temperature: temperature,
        humidity: humidity,
        co2: co2,
        pm25: pm25,
        formaldehyde: formaldehyde
      });
    }
    
    return data;
  },
  
  /**
   * 查看详情
   */
  viewDetail: function(e) {
    const index = e.currentTarget.dataset.index;
    const detail = this.data.historyData[index];
    
    wx.navigateTo({
      url: `../detail/detail?date=${detail.date}`,
      fail: function(err) {
        console.error('跳转到详情页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },
  
  /**
   * 返回上一页
   */
  navigateBack: function() {
    wx.navigateBack({
      fail: function() {
        wx.switchTab({
          url: '../airquality/airquality'
        });
      }
    });
  },
  
  /**
   * 切换月份
   */
  changeMonth: function(e) {
    const direction = e.currentTarget.dataset.direction;
    const now = new Date();
    let year = parseInt(this.data.currentMonth.split('年')[0]);
    let month = parseInt(this.data.currentMonth.split('年')[1].split('月')[0]);
    
    if (direction === 'prev') {
      month--;
      if (month < 1) {
        month = 12;
        year--;
      }
    } else {
      month++;
      if (month > 12) {
        month = 1;
        year++;
      }
    }
    
    // 限制不能超过当前月份
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1;
    if (year > currentYear || (year === currentYear && month > currentMonth)) {
      wx.showToast({
        title: '已是最新月份',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      currentMonth: `${year}年${month}月`
    });
    
    // 重新加载数据
    this.loadHistoryData();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadHistoryData();
    wx.stopPullDownRefresh();
  },  // 这里添加了逗号

  /**
   * 导出数据
   */
  exportData: function() {
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none',
      duration: 2000
    });
  }
})